package cn.tac.test.seo.rpc.client.feign;

import cn.tac.test.seo.rpc.client.feign.util.EncodeUtils;
import cn.tac.test.seo.rpc.core.pojo.Foo;
import cn.tac.test.seo.rpc.core.pojo.FooQuery;
import cn.tac.test.seo.rpc.core.pojo.FullResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.*;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import feign.slf4j.Slf4jLogger;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * @author tac
 * @since 20/12/2017
 */
@Headers("Accept: application/json")
public interface FooClient {
    @RequestLine("GET /foo/{id}")
    Foo get(@Param("id") String id);

    @RequestLine("GET /foo/full/{id}")
    FullResult<Foo> fullGet(@Param("id") String id);

    default List<Foo> query(FooQuery query) {
        return query(EncodeUtils.toQueryMap(query));
    }

    @Deprecated
    @RequestLine("GET /foo/query")
    List<Foo> query(@QueryMap Map<String, Object> query);

    @RequestLine("GET /foo/listAll")
    List<Foo> listAll();

    @RequestLine("PUT /foo")
    @Headers("Content-Type: application/json")
    String create(Foo foo);

    @RequestLine("PUT /foo")
    @Headers("Content-Type: application/json")
    String create(Map<String, Object> foo);

    static FooClient connect(String url) {
        return connect(url, "yyyy-MM-dd HH:mm:ss");
    }

    static FooClient connect(String url, String dateFormat) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat(dateFormat));
        JacksonDecoder decoder = new JacksonDecoder(objectMapper);
        JacksonEncoder encoder = new JacksonEncoder(objectMapper);

        return Feign.builder()
                .logger(new Slf4jLogger())
                .logLevel(Logger.Level.FULL)
                .encoder(encoder)
                .decoder(decoder)
                .target(FooClient.class, url);
    }
}
